package com.digitalchina.lxnsy.activity.old;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.alipay.ALiKeys;
import com.digitalchina.lxnsy.alipay.AuthResult;
import com.digitalchina.lxnsy.alipay.OrderInfoUtil2_0;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.UserInfo3rdPatyVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2019/1/5 11:39
 * 修改备注：
 * ================================================
 */
public class AuthLoginListActivity extends BaseActivity {

    @Bind(R.id.tv_name_wx)
    TextView tvNameWx;
    @Bind(R.id.tv_name_ali)
    TextView tvNameAli;

    private static final int WX_AUTH = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private String openId = "";
    private String unionid = "";
    private String nickname = "";

    private String bindType = "";


    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_auth_login_list);
        setTitle("授权登录");
    }

    @Override
    public void initMember() {
        BusinessAccount.get3rdUserInfo(this, mHandler);
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                dismissDialog();
                switch (msg.what) {
                    case MSG.MSG_GET_3RD_USER_INFO_SUCCESS: // 绑定列表
                        List<UserInfo3rdPatyVO> list = FastJsonUtil.getListBean(msg.obj.toString(), "userInfo3rdPatyList", UserInfo3rdPatyVO.class);
                        if (list != null) {
                            // 两者都验证
                            if (list.size() == 2) {
                                tvNameWx.setText("已绑定");
                                tvNameAli.setText("已绑定");
                            } else if (list.size() == 1) {
                                String type = list.get(0).getAccountType();
                                if ("WX".equals(type)) {
                                    tvNameWx.setText("已绑定");
                                } else
                                    tvNameAli.setText("已绑定");
                            }
                        }
                        break;
                    case MSG.MSG_GET_3RD_USER_INFO_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_BIND_3RD_USER_INFO_SUCCESS: // 绑定成功
                        showToast("绑定成功");
                        if ("WX".equals(bindType)) {
                            tvNameWx.setText("已绑定");
                        } else
                            tvNameAli.setText("已绑定");
                        break;
                    case MSG.MSG_BIND_3RD_USER_INFO_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case WX_AUTH: // 微信授权
                        BusinessAccount.bind3rdUserInfo(AuthLoginListActivity.this, openId, unionid, "WX", nickname, mHandler);
                        break;
                    case SDK_AUTH_FLAG:
                        AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                        String resultStatus = authResult.getResultStatus();

                        // 判断resultStatus 为“9000”且result_code
                        // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                        if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                            // 获取alipay_open_id，调支付时作为参数extern_token 的value
                            // 传入，则支付账户为该授权账户
                            //success=true&result_code=200&app_id=2016080301700871&auth_code=e7397a7ffce942bc8febe903a1d3ZF30&scope=kuaijie&alipay_open_id=20881023785173807774131263013030&user_id=2088421445732305&target_id=nongkechengka@126.com
                            String str1 = authResult.getResult().substring(0, authResult.getResult().lastIndexOf("="));
                            nickname = authResult.getResult().substring(str1.length() + 1);
                            String openId = authResult.getAlipayOpenId();
                            String userId = authResult.getuserId();
                            BusinessAccount.bind3rdUserInfo(AuthLoginListActivity.this, openId, userId, "ZFB", nickname, mHandler);
                        } else {
                            // 其他状态值则为授权失败
                            showToast("授权失败");
                        }
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.rl_auth_wx, R.id.rl_auth_alipay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_auth_wx:

                break;
            case R.id.rl_auth_alipay:
                bindAliPay();
                break;
        }
    }




    // 支付宝登录
    private void bindAliPay() {
        bindType = "AliPay";
        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * authInfo 的获取必须来自服务端；
         */
        Map<String, String> authInfoMap = OrderInfoUtil2_0.buildAuthInfoMap(ALiKeys.PID, ALiKeys.APPID, ALiKeys.TARGET_ID, false);
        String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);

        String privateKey = ALiKeys.RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(authInfoMap, privateKey, false);
        final String authInfo = info + "&" + sign;
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(AuthLoginListActivity.this);
                // 调用授权接口，获取授权结果
                String result = authTask.auth(authInfo, true);
                Map<String, String> map = AuthResult.a(result);

                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = map;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }
}
